package com.example.blog.service.impl;

import com.example.blog.dao.blogRepository;
import com.example.blog.pojo.blog;
import com.example.blog.service.blogService;
import com.example.blog.util.markdownUtile;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class blogServiceImpl implements blogService {

    @Autowired
    blogRepository blogRepository;

    @Override
    public blog getBlog(Integer id) {
        return blogRepository.findById(id);
    }

    @Override
    public blog getBlogMarkdown(Integer id) {
        blog blog = blogRepository.findById(id);
        blog.setUser_id(1);
        blog.setType_id(blog.getType().getId());
        blog.setView(blog.getView()+1);
        blogRepository.update(blog);
        markdownUtile markdownUtile = new markdownUtile();
        String html = markdownUtile.markdownToHtmlExtensions(blog.getContent());
        blog.setContent(html);
        return blog;
    }

    @Override
    public List<blog> getBlog(String title) {
        return blogRepository.findByTitle(title);
    }

    @Override
    public List<blog> getBlog(String title, boolean recommend) {
        return blogRepository.findByTitleAndRecommend(title,recommend);
    }

    @Override
    public List<blog> getBlog(String title, String type, boolean recommend) {
        return blogRepository.findByTitleAndTypeAndRecommend(title,type,recommend);
    }

    @Override
    public List<blog> listBlog() {
        return blogRepository.findAll();
    }

    @Override
    public List<blog> getBlogByType(String type) {

        return blogRepository.findByType(type);
    }

    @Override
    public List<blog> getBlogByTag(Integer tag) {
        return blogRepository.findByTag(tag);
    }

    @Transactional
    @Override
    public void deleteBlog(Integer id) {
        blogRepository.deleteById(id);
    }

    @Transactional
    @Override
    public void saveBlog(blog blog) {
        blogRepository.save(blog);
    }

    @Transactional
    @Override
    public void updateBlog(Integer id, blog blog) throws NotFoundException {
        blog b = blogRepository.findById(id);
        if (b == null){
            throw new NotFoundException("不存在该博客");
        }else {
            blogRepository.update(blog);
        }
    }
}
